//! @Author: DengLibin
//! @Date: Create in 2024-07-22 14:48:23
//! @Description:

use std::sync::Arc;

use axum::{routing::post, Extension, Json, Router};
use bcrypt::verify;
use serde_json::{json, Value};

use crate::{
    app::AppState, entity::user, pojo::dto::LoginDto, service::user_service, web::Resdata,
};

pub async fn route(router: Router) -> Router {
    let router = router.route("/tenant/login", post(login));
    router
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-22 14:54:18
/// @Description: 登录
pub async fn login(
    Extension(state): Extension<Arc<AppState>>,
    Json(login_dto): Json<LoginDto>,
) -> Json<Value> {
    let r = user_service::get_by_login_name(login_dto.user_login_name.as_str(), &state.pool).await;
    if let Err(_) = r {
        return Json(json!(Resdata::<String>::err("内部异常".into())));
    }
    let user_o = r.unwrap();
    match user_o {
        Some(user) => {
            if let Some(passwords) = &user.passwords {
                let r = verify(login_dto.passwords.as_str(), &passwords);
                if let Ok(b) = r {
                    if b {
                        return Json(json!(Resdata::<user::User>::ok_result(Ok(user))));
                    }
                }
            }

            return Json(json!(Resdata::<String>::err("密码错误".into())));
        }
        None => {
            return Json(json!(Resdata::<String>::err("用户不存在".into())));
        }
    }
}
